# -*- coding: utf-8 -*-


import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time
	   

##General vars
__plugin__ = "kidsTV"
__author__ = "Shmulik"
__USERAGENT__ = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20950708 Firefox/4.0.1'
__XBMC_Revision__ = ""


def getMatches(url,pattern):
  matches=re.compile(pattern).findall(getData(url))
  return matches

def getData(url):
  cachePath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','pages',urllib.unquote(url).replace(':','').replace('?','').replace('/',' - ')) )
  if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= 1):
	f = open(cachePath, 'r')
	ret = f.read()
	f.close()
	return ret
  req = urllib2.Request(url)
  req.add_header('User-Agent', __USERAGENT__)
  req.add_header('Accept-Charset','utf-8')
  response = urllib2.urlopen(req)
  data=response.read()
  response.close()
  f = open(cachePath, 'w')
  f.write(data)
  f.close()
  
  return data
def getSeriesList():
  matches = getMatches('http://www.kidstv.co.il/vod','class="view-field view-data-field-serial-logo-fid"><a href="(.*?)" title="(.*?)".*?><img src="(.*?)"')
  for url,name,img in matches:
	name=urllib.unquote(name)
	name=name.replace("&#039;","'").replace("&quot;",'"').replace('_',' ');
	u=sys.argv[0]+"?url=http://www.kidstv.co.il"+urllib.quote_plus(url)+"&mode=1&name="+urllib.quote_plus(name)
	li=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=img)
	li.setInfo( type="Video", infoLabels={ "Title": urllib.unquote(name) } )
	xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)
  xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

def getSeasons(url,name):
  #need to check if there a "s##" in url if not so there is just one episode
  if (mode==2):
	getEpisodeList(url)
	return
  seasons=getMatches(url,'<a href="(.*?)" class="seasons_tabs.*?">(.*?)</a>')
  if len(seasons)==0:
	getEpisodeList(url)
	return
  serName = name[:-1]
  for url,name in seasons:
	u=sys.argv[0]+"?url=http://www.kidstv.co.il"+urllib.quote_plus(url)+"&mode=2&name="+urllib.quote_plus(name)
	li=xbmcgui.ListItem(urllib.unquote(name), iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
	li.setInfo( type="Video", infoLabels={ "Title":urllib.unquote(name) } )
	xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)
  xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

def getEpisodeList(url):
  pat = '<a href="(.*?)" class=".*?"><img src="(.*?)" alt="" title=""  class="imagecache imagecache-100X80_scale_crop" /></a><div>(.*?)</div>'
  matches = getMatches(url,pat)
  for url,pic,title in matches:
	title = urllib.unquote(title.replace('<br />',' ').replace('</ br>',' '))
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode=3&name="+urllib.quote_plus(title)
	liz=xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=pic)
	liz.setInfo( type="Video", infoLabels={ "Title": title } )
	#liz.setProperty('IsPlayable', 'true')
	xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
  xbmcplugin.setContent(int(sys.argv[1]), 'episodes')

def getAddress(url):
  url= getMatches("http://www.kidstv.co.il"+url," src='http://(rr.d.3dcdn.com/embed/vod/.*?)'></iframe>")[0]
  url= getMatches("http://www.kidstv.co.il"+url,'url: "(http://locator.3dcdn.com/vod/.*?/vod.smil)"')[0]
  url = getMatches(url,'<video src="(.*?)" system-bitrate="700" width="1024">')[0]    
  return "rtmp://il-m1.d.3dcdn.com:443/ktv_vod app=ktv_vod/  swfvfy=true swfUrl=http://rr.d.3dcdn.com/player/swf/flowplayer.commercial-Ã3.2.18.swf tcurl=rtmp://il-m1.d.3dcdn.com:443/ktv_vod pageurl=http://rr.d.3dcdn.com/embed/vod/ktv-ry12r1-x3/480/390?folder_id=23 playpath="+url
  
def get_params():
		param=[]
		paramstring=sys.argv[2]
		if len(paramstring)>=2:
				params=sys.argv[2]
				cleanedparams=params.replace('?','')
				if (params[len(params)-1]=='/'):
						params=params[0:len(params)-2]
				pairsofparams=cleanedparams.split('&')
				param={}
				for i in range(len(pairsofparams)):
						splitparams={}
						splitparams=pairsofparams[i].split('=')
						if (len(splitparams))==2:
								param[splitparams[0]]=splitparams[1]
								
		return param

		
params=get_params()
url=None
name=None
mode=None

try:
		url=urllib.unquote_plus(params["url"])
except:
		pass
try:
		name=urllib.unquote_plus(params["name"])
except:
		pass
try:
		mode=int(params["mode"])
except:
		pass

if mode==None or url==None or len(url)<1:
	getSeriesList()
elif mode==1 or mode ==2:
	getSeasons(url,name)
elif mode==3:
	#xbmcplugin.setResolvedUrl(succeeded = True, listitem=xbmcgui.ListItem(path=getFlvAddress(url)))
	xbmc.Player().play(getAddress(url))


xbmcplugin.endOfDirectory(int(sys.argv[1]))